import router from '../router/index'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, setUrl } from '../utils/auth'
NProgress.configure({ showSpinner: false }) // NProgress配置

const whiteList = ['/login', '/404', '/pageAuth', '/scan', '/qrcode'] // 没有重定向白名单

// eslint-disable-next-line space-before-function-paren
router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()
  function getPageTitle(pageTitle: any) {
    return `${pageTitle}`
  }
  // set page title
  document.title = getPageTitle(to.meta.title)
  // // 确认用户是否已登录
  const hasToken = getToken()
  /* has no token*/

  if (whiteList.includes(to.path)) {
    if (to.path === '/login' && hasToken) {
      next('/confirm_work')
      return
    }
    // 在免费登录白名单中，直接进入
    next()
    return
  }
  if (hasToken) {
    next()
    return
  }
  // 其他没有访问权限的页面被重定向到登录页面
  // sessionStorage.setItem('beforeLoginUrl', to.fullPath)
  setUrl(to.fullPath)
  next(`/login`)
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
